package com.example.pixelyear.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.example.pixelyear.R
import com.example.pixelyear.utils.UIUtils

class ChooseColorView @JvmOverloads constructor(
    context: Context,
    attributes: AttributeSet? = null,
    defaultStyle: Int = 0
) :
    View(context, attributes, defaultStyle) {

    private val mPaint by lazy {
        Paint().also {
            it.strokeWidth = 8f
            it.flags = Paint.ANTI_ALIAS_FLAG
        }
    }

    private val boxWidth = UIUtils.getDimensionFloat(R.dimen.dp_30)
    private val boxHeight = UIUtils.getDimensionFloat(R.dimen.dp_30)
    private val choosePadding = UIUtils.getDimensionFloat(R.dimen.dp_4)
    private var choose = false
    private var text = ""

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var w = 0
        var h = 0

        if (widthMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            w = UIUtils.getDimension(R.dimen.dp_40)
        }

        if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            h = UIUtils.getDimension(R.dimen.dp_40)
        }
        setMeasuredDimension(w, h)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawRect(
            0f + choosePadding,
            0f + choosePadding,
            boxWidth - choosePadding,
            boxHeight - choosePadding,
            mPaint
        )

        if (choose) {
            //上横
            canvas?.drawLine(0f, 0f, boxWidth + choosePadding - 1, 0f, mPaint)

            //下横
            canvas?.drawLine(0f, boxHeight - 1, boxWidth + choosePadding, boxHeight - 1, mPaint)

            //左竖
            canvas?.drawLine(0f, 0f, 0f, boxHeight - 1, mPaint)
            //右竖
            canvas?.drawLine(boxWidth - 1, 0f, boxWidth - 1, boxHeight, mPaint)
        }
    }


    fun choose() {
        choose = true
        requestLayout()
    }

    fun notChoose() {
        choose = false
        requestLayout()
    }

    fun setColor(c: Int, t: String) {
        text = t
        mPaint.color = c
        requestLayout()
    }
}
